<template>
  <div>
    <!-- drawer 取消按钮 时，关闭弹窗 -->
    <el-drawer
      :title="title"
      :visible.sync="visible"
      size="60%"
      :append-to-body="true"
      @close="clearDialog()"
      :wrapperClosable="false"
      v-loading="loding"
      :close-on-click-modal="false"
    >
      <div class="pack">
        <ele-form
          v-model="dialogfrom"
          v-bind="formConfig"
          ref="form"
          :key="time"
        >
          <template v-slot:tip1="">
            <div class="title">
              <div></div>
              <h3>{{ $i18n.t("mesUniqueCodePrinting.baseInfo") }}</h3>
            </div>
          </template>
          <template v-slot:tip2="">
            <div class="title">
              <div></div>
              <h3>{{ $i18n.t("mesUniqueCodePrinting.liveCodeInformation") }}</h3>
            </div>
          </template>
          <template v-slot:tip3="">
            <div class="title">
              <div></div>
              <h3>{{ $i18n.t("mesUniqueCodePrinting.printInformation") }}</h3>
            </div>
          </template>
        </ele-form>
        <div slot="footer" class="dialog-footer">
          <!-- 取消 -->
          <el-button @click="clearDialog()">{{
            $t("common.cancel")
          }}</el-button>

          <!-- 清除唯一码 -->
          <!--   v-if="dialogfrom.isCreateBarcode == 1" -->
          <el-button
            type="danger"
            :disabled="!(dialogfrom.isCreateBarcode == 1)"
            @click="notesdialogFormVisible = true"
            >{{ $t("printBoxCode.clearUniqueCode") }}
          </el-button>
          <!-- 生码 -->

          <!-- v-if="dialogfrom.quantity != dialogfrom.amount" -->
          <el-button
            type="primary"
            @click="creatBoxCode()"
            :disabled="!(dialogfrom.quantity != dialogfrom.amount)"
            >{{ $t("printBoxCode.create") }}</el-button
          >
          <!--  v-if="
              dialogfrom.printQuantity > 0 &&
              dialogfrom.quantity != dialogfrom.amount
            " -->
          <el-button
            :disabled="
              !(
                dialogfrom.printQuantity > 0 &&
                dialogfrom.quantity != dialogfrom.amount
              )
            "
            type="primary"
            @click="creatBoxCode(true)"
            >{{ $i18n.t("mesUniqueCodePrinting.createPrint") }}</el-button
          >

          <!--      v-if="
              dialogfrom.isCreateBarcode == 1 &&
              Number(dialogfrom.quantityNotPrinted > 0) &&
              dialogfrom.quantityPrinted != dialogfrom.amount
            " -->
          <el-button
            type="success"
            :disabled="
              !(
                dialogfrom.isCreateBarcode == 1 &&
                Number(dialogfrom.quantityNotPrinted > 0) &&
                dialogfrom.quantityPrinted != dialogfrom.amount
              )
            "
            plain
            @click="handleShow()"
            >{{ $i18n.t("mesUniqueCodePrinting.print") }}</el-button
          >

          <!--   v-if="
              dialogfrom.isCreateBarcode == 1 &&
              Number(dialogfrom.quantityPrinted > 0)
            " -->
          <el-button
            :disabled="
              !(
                dialogfrom.isCreateBarcode == 1 &&
                Number(dialogfrom.quantityPrinted > 0)
              )
            "
            type="success"
            plain
            @click="repairPrint()"
            >{{ $i18n.t("mesUniqueCodePrinting.reprint") }}</el-button
          >
        </div>
      </div>
    </el-drawer>
    <el-dialog
      width="20%"
      :title="$t('capacityCode.printFilter')"
      :visible.sync="innerVisible"
      :append-to-body="true"
      @close="clearFormDialog()"
      v-loading="loding"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules">
        <el-form-item
          :label="$i18n.t('mesUniqueCodePrinting.printQuantity')"
          label-width="85px"
          prop="amount"
        >
          <el-input-number
            size="small"
            v-model="form.amount"
            :step="1"
            :min="1"
            :max="Number(maxnum)"
          ></el-input-number>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="clearFormDialog()">{{
          $t("common.cancel")
        }}</el-button>
        <el-button type="primary" @click="handleRequest">{{
          $t("common.submit")
        }}</el-button>
      </div>
    </el-dialog>
    <!--  goodsCode: dialogfrom.prodCode, -->
    <templateSelect
      ref="templateSelect"
      v-model="dialogfrom.barcodePrintTempCode"
      :searchData="{
        businessTypeCode: 'PRINT_MES_PC_UNIQUE_CODE',
      }"
      @select="
        (data) => {
          $set(dialogfrom, 'barcodePrintTemp', data.name);
        }
      "
    ></templateSelect>

    <!-- 清除箱码备注提交弹窗 -->
    <ele-form-dialog
      ref="notesFormData"
      width="400px"
      v-model="remarkForm"
      :formDesc="{
        remark: {
          type: 'textarea',
          label: $i18n.t('mesUniqueCodePrinting.remark2'),
          layout: 24,
          required: true,
        },
      }"
      :request-fn="clearBoxcode"
      :visible.sync="notesdialogFormVisible"
      :title="$i18n.t('mesUniqueCodePrinting.remind')"
    ></ele-form-dialog>
  </div>
</template>

<script>
import {
  getBarcodePrintTempList,
  printTemplateInfo,
  splitPrintList,
  getBoxCountNes as getBoxCount,
  clearBoxcode,
  genCodeAndGetPrintBatch, //生码新
  creatBoxCode, //生码
  selectCommonProduceRelByProduce,
  getPrintList,
} from "@/api/print/mesProdBarcodePrint";

import { setPrintData } from "@/utils/judge.js";
import templateSelect from "@/components/templateSelect/index.vue";
let arrBarcodePrintingList2 = [];
export default {
  name: "barcodePrintingAddModel",
  watch: {
    visible(val, oldVal) {
      if (!val) {
        this.$nextTick(() => {
          this.$refs.form.resetForm();
        });
        this.barcodeInfo = {};
      }
    },
  },
  props: {
    title: {
      type: String,
      default: "",
    },
  },
  components: { templateSelect },
  data() {
    let that = this;
    return {
      time: 1,
      loding: false,
      time: 0,
      notesdialogFormVisible: false,
      remarkForm: {},
      formConfig: {
        span: 24,
        labelPosition: "right",
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        formDesc: {
          tip1: {
            type: "text",
            layout: 24,
          },
          orderCode: {
            type: "input",
            label: $i18n.t("mesUniqueCodePrinting.workOrderCode"),
            layout: 12,
            required: true,
            disabled: true,
          },
          prodCode: {
            type: "input",
            label: this.$i18n.t("mesUniqueCodePrinting.prodCode"),
            layout: 12,
            disabled: true,
          },
          prodName: {
            type: "input",
            label: $i18n.t("mesUniqueCodePrinting.goodsName"),
            layout: 12,
            required: true,
            disabled: true,
          },
          amount: {
            type: "number",
            label: $i18n.t("mesUniqueCodePrinting.amount"),
            layout: 12,
            required: true,
            disabled: true,
            attrs: {
              stepStrictly: true,
              controlsPosition: "right",
              min: 0,
            },
          },
          tip2: {
            type: "text",
            layout: 24,
          },
          codeStrategy: {
            type: "select",
            label: $i18n.t("mesUniqueCodePrinting.codeStrategy"),
            layout: 12,

            prop: {
              value: "codeStrategyCode",
              text: "codeStrategyDescription",
            },
            optionsLinkageFields: ["prodCode"],
            options: async (data) => {
              const params = {
                goodsCode: data.prodCode,
                templateType: "unique_code",
                type: "codeStrategy",
              };
              const list = await selectCommonProduceRelByProduce(params);
              return list.data.result;
            },
            rules: [
              {
                required: true,
                validator: (rule, value, callback) => {
                  setTimeout(() => {
                    if (this.dialogfrom.codeStrategy) {
                      callback();
                    } else {
                      callback(
                        new Error(
                          $i18n.t("mesUniqueCodePrinting.pleaseSelectCodeRules")
                        )
                      );
                    }
                  }, 500);
                },
                trigger: ["change", "blur"],
              },
            ],

            // vif(data) {
            //   return data.isCreateBarcode == 0 ? true : false;
            // },
            disabled: (data) => {
              return data.isCreateBarcode == 0 ? false : true;
            },
          },
          quantity: {
            type: "number",
            label: $i18n.t("mesUniqueCodePrinting.quantity"),
            layout: 12,
            required: true,
            disabled: true,
            attrs: {
              stepStrictly: true,
              controlsPosition: "right",
              min: 0,
            },
          },
          printQuantity: {
            type: "number",
            label: $i18n.t("mesUniqueCodePrinting.printQuantity2"),
            layout: 12,
            required: true,
            attrs: {
              stepStrictly: true,
              controlsPosition: "right",
              min: 0,
              max: 999999999,
            },
            disabled: (data) => {
              return data.quantity == data.amount ? true : false;
            },
            vif(data) {
              return data.quantity == data.amount ? false : true;
            },
          },
          tip3: {
            type: "text",
            layout: 24,
          },
          barcodePrintTemp: {
            type: "input",
            label: $i18n.t("mesUniqueCodePrinting.barcodePrintTemp"),
            layout: 12,
            disabled: (data) => {
              return data.isCreateBarcode == 0 ? false : true;
            },
            attrs: {
              readonly: true,
            },
            required: true,
            slots: {
              append(h) {
                return (
                  <el-button
                    icon="el-icon-search"
                    disabled={
                      that.dialogfrom.isCreateBarcode == 0 ? false : true
                    }
                    onClick={() => {
                      that.$refs.templateSelect.show();
                    }}
                  ></el-button>
                );
              },
            },
          },

          // count: {
          //   type: "number",
          //   label: $i18n.t("printBoxCode.volume"),
          //   layout: 8,
          //   required: true,
          //   attrs: {
          //     stepStrictly: true,
          //     controlsPosition: "right",
          //     min: 1,
          //     max: 9999999,
          //   },
          //   disabled: (data) => {
          //     return data.isCreateBarcode == 1 ? true : false;
          //   },
          //   on: {
          //     change: (data) => {
          //       that.countChange(data);
          //     },
          //   },
          // },
          quantityPrinted: {
            type: "number",
            label: $i18n.t("mesUniqueCodePrinting.printedQty"),
            layout: 12,
            required: true,
            disabled: true,
          },
          quantityNotPrinted: {
            type: "number",
            label: $i18n.t("mesUniqueCodePrinting.quantityNotPrinted"),
            layout: 12,
            required: true,
            disabled: true,
          },
        },
      },
      barcodeInfo: {},
      dialogfrom: {},
      visible: false,
      loading: false,
      innerVisible: false,
      form: {
        amount: 0,
      },
      rules: {
        amount: [
          {
            required: true,
            message: $i18n.t("mesUniqueCodePrinting.printingQuantity"),
            trigger: "blur",
          },
        ],
      },
      maxnum: 9999,
      list: [],
    };
  },
  methods: {
    //初始化
    init(params) {
      this.dialogfrom = params;
      this.time = new Date().getTime();
      this.dialogfrom.codeStrategy = params.orderBarcodeRuleCode;
      //  this.barcodeInfo.barcode = "";
      this.visible = true;
      // let { quantity } = this.dialogfrom;
      // this.dialogfrom.printQuantity = quantity; //条码数量=计划数量
      this.$nextTick(() => {
        //  this.formConfig.formDesc.count.attrs.max = quantity
        this.getBoxCount();
      });
    },
    setBarcodePrintTempRequired(bool=false) {
      this.$set(this.formConfig.formDesc.barcodePrintTemp, "required", bool);
    },
    // 补打印
    repairPrint() {
      this.clearDialog();
      this.$parent.modelTitle = $i18n.t("mesUniqueCodePrinting.reprint");
      // debugger;
      this.$parent.repairPrint({
        ...this.dialogfrom,
      });
    },
    /**
     * @author bing
     * @since 2022-11-18 14:47:33
     *  箱码打印-获取条码数量，已打印、未打印数量
     */
    async getBoxCount() {
      let res = await getBoxCount(this.dialogfrom.id);
      let { quantity, barcodeCreateCount, barcodePrintCount } = res.data.result;
      this.dialogfrom.amount = quantity;
      this.dialogfrom.quantity = barcodeCreateCount;
      this.dialogfrom.quantityPrinted = barcodePrintCount;
      this.dialogfrom.quantityNotPrinted =
        Number(barcodeCreateCount || 0) - Number(barcodePrintCount || 0);

      this.countChange(this.dialogfrom);

      // if (!quantity) {
      //   this.countChange(this.dialogfrom.count);
      // }
    },

    /**
     * @author bing
     * @since 2022-11-17 11:13:11
     * 清楚箱码
     */
    async clearBoxcode(data) {
      try {
        this.loding = true;
        let res = await clearBoxcode({
          clearReason: data.remark,
          orderCode: this.dialogfrom.orderCode,
        });
        let deflt = this.dialogfrom.count;
        this.dialogfrom.count = 999;
        this.notesdialogFormVisible = false;
        this.$nextTick(() => {
          this.dialogfrom.count = deflt;

          this.getBoxCount();
          this.$set(this.dialogfrom, "isCreateBarcode", 0);
        });
      } catch (err) {
      } finally {
        this.loding = false;
      }
    },

    //修改容量 生码数量
    countChange(data) {
      let { amount, quantity } = data;
      let count = Number(amount || 0) - Number(quantity || 0);
      this.dialogfrom.printQuantity = count;
      this.$set(this.formConfig.formDesc.printQuantity.attrs, "max", count);
    },
    //点击生码按钮
    creatBoxCode(bool) {

      // this.setBarcodePrintTempRequired(bool);

      this.$refs.form.validate().then((valid) => {
        let {
          orderCode,
          count,
          amount,
          barcodePrintTemp,
          printQuantity,
          codeStrategy,
          barcodePrintTempCode,
        } = this.dialogfrom;
        let data = {
          orderCode: orderCode, //'生产工单号',
          amount: printQuantity, //'容量',
          codeStrategy,
          barcodePrintTemp: barcodePrintTemp, //'打印条码模板名称',
          barcodePrintTempCode: barcodePrintTempCode,
        };
        this.loding = true;
        genCodeAndGetPrintBatch(data)
          .then((res) => {
            if (res.data.success) {
              // this.$refs.print.$refs.printing.$el.click()
              !bool
                ? this.$message.success($i18n.t("mesUniqueCodePrinting.createSuccess"))
                : null;
              this.$nextTick(async () => {
                await this.getBoxCount();

                this.$set(this.dialogfrom, "isCreateBarcode", 1);
                this.loding = false;
                if (bool) {
                  this.handleShow();
                }
              });
            }
          })
          .catch((err) => {
            this.loding = false;
          });
      });
    },
    clearDialog() {
      this.visible = false;
      this.$emit("refreshList");
    },
    clearFormDialog() {
      this.innerVisible = false;
      this.form.amount = 1;
      this.maxnum = 9999;
    },
    handleShow() {
      if (!this.dialogfrom.barcodePrintTemp) {
        this.$message.warning(
          this.$i18n.t("mesUniqueCodePrinting.barcodePrintTempCheckMsg")
        );
        return;
      }
      this.innerVisible = true;
      this.maxnum = this.dialogfrom.quantityNotPrinted;
      this.form.amount = this.dialogfrom.quantityNotPrinted;
    },
    //点击打印按钮
    handleRequest() {
      if (this.form.amount <= 0) {
        this.$message.warning($i18n.t("mesUniqueCodePrinting.amountCheckMsg"));
        return;
      }
      this.$refs.form.handleSubmitForm();
      this.$refs.form.validate().then((valid) => {
        //判断容量是否为空
        let data = {
          isPrint: 0,
          orderCode: this.dialogfrom.orderCode, //'生产工单号',
          printAmount: this.form.amount,
        };
        data.splitNum = this.dialogfrom.splitNum;
        getPrintList(data).then((res) => {
          if (res.data.success) {
            let list = res.data.result;
            this.clearFormDialog();
            this.clearDialog();
            let { barcodePrintTempCode, barcodePrintTemp } = this.dialogfrom;
            setPrintData(
              {
                code: barcodePrintTempCode,
                name: barcodePrintTemp,
                status: 0,
              },
              list
            );
            this.$router.push("/splitPrint");
          }
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.pack {
  padding: 20px;
  padding-top: 0px;
}
.dialog-footer {
  padding-top: 20px;
  display: flex;
  justify-content: end;
}
.title {
  position: relative;
  left: -145px;
  top: 5px;
  display: flex;
  align-items: center;
  h3 {
    padding-left: 8px;
    font-size: 16px;
    color: #333333;
  }
  & > div {
    width: 5px;
    height: 13px;
    background: #00b39b;
  }
}
/deep/ .el-drawer__body {
  padding-left: 60px;
}
</style>
